import logging
import os, oss2
import configparser
from ..models import file_upload

config = configparser.ConfigParser()
config.read('./libs/system.conf', encoding='utf-8')
oss_conf = config['aliyun']

CUSTOM_ERROR = logging.getLogger('apps.views')


class FileUpload_To_OSS():
    '''上传文件到oss'''

    def __init__(self, env=None, filename=None, filetype=None, childtype=None, *args):
        '''文件相关属性'''
        self.env = env
        self.filename = filename
        self.filetype = filetype
        self.childtype = childtype
        self.Bucket = oss_conf[f'bucket_{env}']
        self.EndPoint = oss_conf[f'endpoint_{env}']
        self.domain = f"{oss_conf[f'url_{env}']}/{self.url_transcoding()}"
        self.key = oss_conf['key']
        self.secret = oss_conf['secret']
        self.auth = oss2.Auth(self.key, self.secret)
        self.bucket = oss2.Bucket(self.auth, self.EndPoint, self.Bucket)

    def url_transcoding(self):
        '''将文件名转为url码，以方便进行url访问或下载'''

        import urllib.parse
        url_code = urllib.parse.quote(self.filename)
        return url_code

    def uploading(self, filepath=None, fileMD5=None):
        '''上传到oss'''

        try:
            if self.childtype == 'banner':
                self.domain = f"{oss_conf['url_prod']}/banner/{self.url_transcoding()}"
                self.bucket.put_object_from_file(f'banner/{self.filename}', f'{filepath}/{self.filename}')
            elif self.childtype == 'icon':
                self.domain = f"{oss_conf['url_prod']}/b_icon/{self.url_transcoding()}"
                self.bucket.put_object_from_file(f'b_icon/{self.filename}', f'{filepath}/{self.filename}')
            elif self.childtype == 'app':
                self.domain = f"{oss_conf[f'url_{self.env}']}/app/{self.url_transcoding()}"
                self.bucket.put_object_from_file(f'app/{self.filename}', f'{filepath}/{self.filename}')
            elif self.childtype == 'national':
                self.domain = f"{oss_conf['url_prod']}/national/{self.url_transcoding()}"
                self.bucket.put_object_from_file(f'national/{self.filename}', f'{filepath}/{self.filename}')
            elif self.childtype == 'partners':
                self.domain = f"{oss_conf['url_prod']}/partner_partner/{self.url_transcoding()}"
                self.bucket.put_object_from_file(f'partner_partner/{self.filename}', f'{filepath}/{self.filename}')
            else:
                self.domain = f"{oss_conf['url_prod']}/{self.url_transcoding()}"
                self.bucket.put_object_from_file(f'{self.filename}', f'{filepath}/{self.filename}')
        except IOError as e:
            CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}')
            return {'msg': f'{self.filename} 上传失败'}

        file_news = file_upload(name=self.filename, file_md5=fileMD5, file_url=self.domain, file_type=self.filetype,
                                child_type=self.childtype, env=self.env)
        file_news.save()
        # 删除上传成功后的本地文件
        os.remove(f'{filepath}/{self.filename}')

        return {'msg': f'file {self.filename} uploaded successfully', 'status': 'success', 'url': self.domain}

    def deleteOssFile(self):
        '''删除oss文件'''

        try:
            if self.childtype == 'banner':
                self.bucket.delete_object(f'banner/{self.filename}')
            elif self.childtype == 'icon':
                self.bucket.delete_object(f'b_icon/{self.filename}')
            elif self.childtype == 'national':
                self.bucket.delete_object(f'national/{self.filename}')
            elif self.childtype == 'partners':
                self.bucket.delete_object(f'partner_partner/{self.filename}')
            elif self.childtype == 'app':
                self.bucket.delete_object(f'app/{self.filename}')
            else:
                self.bucket.delete_object(f'{self.filename}')
        except IOError as e:
            CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}')
            return {'msg': f'{self.filename} 删除失败'}
        else:
            return {'msg': f'{self.filename} 删除成功'}
